import 'package:city_pickers/meta/_province.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'dart:convert';
import '../config/api.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
List data=[];
bool flag=false;
//商品数据请求
getlist()async{
  getgoodslist().then((value) => {
   data=value.data['message'],
   // print(data),
   // flag=true
   if(data==null){

   }else{
     add(1)
   }
  });
}
List map=[];
List m1=[];
List m4=[];
//商品分类数据请求
add(v)async{
 m4=[];
  // print('我是初始化的数据${v}');

 if(v==null){
   v=1;
 }
  SharedPreferences prefs=await SharedPreferences.getInstance();
  prefs.setString('goodslist', json.encode(data));
  map=json.decode(prefs.getString('goodslist'));
   
  map.forEach((item) {
  //  m1=[];
    if(item['type']==v){
     
      m4.add(item);

    }
  });
  m1=m4;
  // print('我是初始化的数据${m1}');
   return m1;
 // print('我是数据${map}');
}
//搜索历史记录
List s=[];
List a=[];
String s1;
Future <void> search(v)async{
SharedPreferences prefs=await SharedPreferences.getInstance();
 //prefs.setString('search', v);
//print(prefs.getString('search'));
//s1.add(prefs.getString('search'));
print(v);
// s1=json.encode(prefs.getString('search'));
// if(s1!=null){
//   print('我进来了${s1}');
// }else{
  
// }
// s=s1??[]??s1;
// print(s1);
 s.add(v);
 s.insert(0, v);
 s=s.toSet().toList();
 prefs.setString('search', json.encode(s));
 getsearch();
print(s);

}
List r=[];
remove()async{
  SharedPreferences prefs=await SharedPreferences.getInstance();
  r=json.decode(prefs.getString('search'));
  //r=r.clear();
  r=[];
  prefs.setString('search', json.encode(r));
}
List se=[];
getsearch()async{
SharedPreferences prefs=await SharedPreferences.getInstance();
se=json.decode(prefs.getString('search'));
print('我是se${se}');
}
List addresList;
class Addressl with ChangeNotifier{
  List addres_list;
  //收货人地址管理
addresslist(username,phone,addsl,city,flag)async{
  SharedPreferences prefs=await SharedPreferences.getInstance();
  var _adds={
    "username":username,
    "phone":phone,
    "addsl":addsl,
    "city":city,
    "flag":flag
  };
  print(_adds);
  var fl=false;
  var c=[];
  var b=prefs.getString('address')??0;
  var temp;
  //var b=json.decode(prefs.getString('address'))??{};
  print(b==0);
  if(b ==0){
   
    if(_adds['flag']){
      c.forEach((item) {
          item['flag']=false;
      });
       c.insert(0, _adds);
    }
   prefs.setString('address', json.encode(c));
     print(c);
  }else{
   // c=b;
    temp=json.decode(b.toString());
    
   List <Map> templist=(temp as List).cast();
   // c.add(_adds);
   if(_adds['flag']){
      templist.forEach((item) {
          item['flag']=false;
      });
       templist.insert(0, _adds);
       prefs.setString('address', json.encode(templist));
    }else{
      templist.add(_adds);
      prefs.setString('address', json.encode(templist));
    }
   //templist.add(_adds);
    
    print(templist);
  }
  //  c=b==null?[]:b;
    // c.add(_adds);
   
  // prefs.remove('address');
   //prefs.setString('address', json.encode(c));
   await getAddress();
}
Future getAddress()async{
  SharedPreferences prefs=await SharedPreferences.getInstance();
  addres_list=json.decode(prefs.getString('address'));
  
  addresList=json.decode(prefs.getString('address'));
  print(addres_list);
  return addres_list;
}
//删除收货人
remove(v)async{
  SharedPreferences prefs=await SharedPreferences.getInstance();
  var ads=[];
 ads =json.decode(prefs.getString('address'));
 if(ads[v]['flag']&&ads.length>=2&&v==0){
   ads[1]['flag']=true;
 }
 ads.removeAt(v);
  prefs.setString('address', json.encode(ads));
   getAddress();
}
}
//下拉加载跟多
int counts=5;
pub1(v)async{
  counts=v;
}
class Pub extends StatefulWidget {
  Pub({Key key}) : super(key: key);

  @override
  _PubState createState() => _PubState();
}

class _PubState extends State<Pub> {
  Timer _time;
  @override
  void initState(){
    super.initState();
    
   setState(() {
      add(1);
      getlist();
      _gettime();
   });
  // _gettime();
  }
 // var time=const Duration(seconds:5);
 var c=1;
  void  _gettime(){
    const time=const Duration(seconds: 5 );
    // _time=new Timer.periodic(time, (timer) { 
    //   //add(1)
    //   print('我是定时器');
    // });
     Timer(time, () {
  //到时回调
  setState(() {
    add(c);
  });
  c++;
  print('afterTimer='+DateTime.now().toString());
});
    }
   ScrollController _scrollController = new ScrollController();
  @override
  Widget build(BuildContext context) {
    return StaggeredGridView.countBuilder(
                shrinkWrap: true,
                controller: _scrollController,
                itemCount: counts,
                // primary: false,
                crossAxisCount: 4,
                mainAxisSpacing: 10.0,
                crossAxisSpacing: 4.0,
                itemBuilder: (context, index) {
                  return
                      // SizedBox(
                      //   height: 150,
                      //   child:
                    m1.length<=0?Center(child:Text('数据加载中')):  InkWell(
                    onTap: () {
                   Navigator.of(context).pushNamed('/goodscommodity',arguments: {"id":m1[index]});
                    },
                    child: Card(
                      elevation: 7.0, //设置阴影
                      clipBehavior: Clip.antiAlias, //设置圆角
                      //  child: AspectRatio(
                      //  aspectRatio: 16 / 10,
                      child: Column(
                        //  mainAxisAlignment: MainAxisAlignment.spaceAround,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          //  Image.network(c[index]['img'],fit:BoxFit.cover)
                          // AspectRatio(aspectRatio: 16/16,child:Image.network(c[index]['img'],fit: BoxFit.cover,),),
                          Expanded(
                              flex: index % 3 != 0 ? 3 : 8,
                              //  height: double.infinity,
                              child: Container(
                                child: Image.network(
                                  // 'http://dbyxs.xyz:3005/uploads/b593883c3adac89564d762ae7b76ad5e',
                                 '${ m1[index]['url'].split(',')[0]}',
                               //c[index]['img'],
                                //this.goods['message'][index]['url'].split(',')[0]||this.ly?m2[index]['url'].split(',')[0]: c[index]['img'],
                             //   this.goods['message'][index]['url'].split(',')[0],
                                  fit: BoxFit.cover,
                                  width: double.infinity,
                                ),
                              )),

                          Container(
                            padding: EdgeInsets.all(5),
                            child: Text(
                              '${m1==[]?'':m1[index]['goodsname']}',
                              style: TextStyle(color: Colors.black26),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.all(5),
                            child: Row(children: <Widget>[
                              Text(
                                '￥${m1[index]['price']}元',
                                style:
                                    TextStyle(color: Colors.red, fontSize: 14),
                              ),
                              SizedBox(
                                width: 5,
                              ),
                              Text('10人付款',
                                  style: TextStyle(
                                      color: Colors.black38, fontSize: 12))
                            ]),
                          ),
                          Container(
                            padding: EdgeInsets.all(5),
                            child: index % 3 != 0 ? Text('特价优惠',style: TextStyle(color: Colors.redAccent),) : Container(),
                          )
                          //  Expanded(
                          //    flex: 1,
                          //    child: Text('价格100'),
                          //  ),
                          // Expanded(child:  Text('我是你的'),flex:1)
                        ],
                      ),
                      // ),
                    ),
                  );
                  // );
                },
                // staggeredTileBuilder: (index) => StaggeredTile.fit(2),
                staggeredTileBuilder: (index) =>
                    // StaggeredTile.count(2, index == 0 ? 2.5 : 3)
                    StaggeredTile.count(2, index == 2 ? 2.5 : 2.8)
                //     // staggeredTileBuilder: (index) => StaggeredTile.fit(2),
                );
  }
}